//
//  MessageList.swift
//  JiaoZiTaxi
//
//  Created by Hu Gang on 2022/10/12.
//

import SwiftUI
import Combine

struct MessageList: View {
  @ObservedObject var order = CarOrder.shared

  var body: some View {
      ScrollViewReader { proxy in
         ScrollView {
            LazyVStack(spacing:0) {
               ForEach(order.messages) { message in
                  if let createAt = message.createAt {
                     Time(date: createAt.date)
                  }

                  MessageRow(message: message, isMe: message.sender.type == .Passenger)
                     .id(message.id)

               }

               Spacer()
                  .id("bottom")
            }
            .background(Color("light_gray"))
         }.onChange(of: order.messages) { _ in
            withAnimation {
               proxy.scrollTo("bottom", anchor: .bottom)
               proxy.scrollTo(order.messages.last?.id, anchor: .bottom)
            }
         }
         .onAppear {
            withAnimation {
               proxy.scrollTo("bottom", anchor: .bottom)
               proxy.scrollTo(order.messages.last?.id, anchor: .bottom)
            }
         }
      }
    .onAppear(perform: load)
  }

  func load() {
    guard CarOrder.shared.messages.isEmpty else { return }
    //messages = Message.all
  }

  struct Time: View {
    let date: Date

    var body: some View {
      Text(date.formatString)
        .foregroundColor(Color("chat_time"))
        .font(.system(size: 14,weight: .medium))
        .frame(maxWidth:.infinity)
        .padding(.vertical,4)
    }
  }
}

struct MessageList_Previews: PreviewProvider {
  static var previews: some View {
    MessageList()
  }
}
